package com.kc.sjwh.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.kc.sjwh.dao.AppDao;
import com.kc.sjwh.dao.ResDao;
import com.kc.sjwh.dao.RoleDao;
import com.kc.sjwh.dao.RoleResDao;
import com.kc.sjwh.dao.RoleUserDao;
import com.kc.sjwh.entity.po.Role;
import com.kc.sjwh.entity.po.RoleRes;
import com.kc.sjwh.other.Page;
import com.kc.sjwh.other.QueryParam;
import com.kc.sjwh.other.Tool;

/**
 * 用户service
 * @author zhangguihua(hua7381@163.com)
 * date: 2017年8月4日
 */
@Service
public class RoleService {
	static Logger logger = Logger.getLogger(RoleService.class);
	@Autowired
	RoleDao roleDao;
	@Autowired
	ResDao resDao;
	@Autowired
	RoleResDao roleResDao;
	@Autowired
	RoleUserDao roleUserDao;
	@Autowired
	AppDao appDao;

	public Page<Role> getPage(int pageSize, int pageNum, Map<String, String> param) {
		QueryParam q = new QueryParam(pageSize, pageNum).setOrder("t.cjsj desc, t.id");
		
		//添加动态的查询条件
		String v = null;
		v = param.get("keyword");
		if(StringUtils.isNotEmpty(v)) {
			q.addCondition("mc", "like", "%"+v+"%");
		}
		v = param.get("yyid");
		if(StringUtils.isNotEmpty(v)) {
			q.put("yyid", v);
		}
		
		return roleDao.getPage("getBo", q);
	}
	
	public Map load4Update(String id) {
		Role one = roleDao.getOne("getBo", new QueryParam().put("id", id));
		
		//加载资源s
		List<RoleRes> list = roleResDao.getList(new QueryParam().put("jsid", id));
		List<String> zyids = new ArrayList<String>();
		for(RoleRes rr : list) {
			zyids.add(rr.getZyid());
		}
		
		Map m = new HashMap();
		m.put("one", one);
		m.put("zyids", StringUtils.join(zyids, ","));
		m.put("resList", resDao.getList(new QueryParam().put("yyid", one.getYyid())));
		return m;
	}

	public void add(Role one) {
		one.setId(Tool.getUuid());
		roleDao.add(one);
	}

	public void update(Role one, String zyids) {
		//清空资源关联s
		roleResDao.deleteByJsid(one.getId());
		//添加资源关联s
		for(String zyid : zyids.split(",")) {
			roleResDao.add(one.getId(), zyid);
		}
		
		one.setGxsj(new Date());
		roleDao.update(one, "id");
	}

	public void delete(String id) {
		Role old = roleDao.getOne(new QueryParam().put("id", id));
		if("admin".equals(old.getDm())) {
			throw new IllegalArgumentException("管理员为固定角色，不可删除");
		}
		
		//级联删除
		roleUserDao.deleteByJsid(id);
		roleResDao.deleteByJsid(id);
		
		int n = roleDao.delete(id);
		if(n == 0) {
			throw new IllegalArgumentException("要删除的记录不存在");
		}
	}
	
}
